#include<stdio.h>
#include <stdlib.h>
#include <conio.h>
#include <windows.h>
#include <time.h>
#define M 25
#define N 80
int a[M][N];
int speed = 10;
int k = 0;


void gotoxy(int x,int y)  //光标移动到(x,y)位置
{
    HANDLE handle = GetStdHandle(STD_OUTPUT_HANDLE);
    COORD pos;
    pos.X = x;
    pos.Y = y;
    SetConsoleCursorPosition(handle,pos);
}

void HideCursor() // 用于隐藏光标
{
	CONSOLE_CURSOR_INFO cursor_info = {1, 0};  // 第二个值为0表示隐藏光标
	SetConsoleCursorInfo(GetStdHandle(STD_OUTPUT_HANDLE), &cursor_info);
}

void start(){
	int i, j;
	for (i = 0; i < M; i ++){
		for (j = 0; j < N; j ++){
			a[i][j] = rand() % 2;
		}
	}
	srand((unsigned int)time(NULL));


	HideCursor(); // 隐藏光标		

}



void show(){
	gotoxy(0,0);
	int i, j;
	for (i = 0; i < M; i ++){
		for (j = 0; j < N; j ++){
			if (a[i][j] == 1)
				printf ("*");
			else
				printf (" ");

		}
		printf ("\n");
	}

}

void update(){
	int i, j;
	int NewCells[M][N]; // 下一帧的细胞情况
	int NeibourNumber; //统计邻居的个数
	k++;
	if (k >= speed){
	for (i = 1; i < M - 1; i ++){
		for (j = 1; j < N - 1; j ++){
			NeibourNumber = a[i-1][j-1] + a[i-1][j] + a[i-1][j+1]
				+ a[i][j-1] + a[i][j+1] + a[i+1][j-1] + a[i+1][j] + a[i+1][j+1];
			if (NeibourNumber==3)
				NewCells[i][j] = 1;  
			else if (NeibourNumber==2)
				NewCells[i][j] = a[i][j];
			else
				NewCells[i][j] = 0;
			
		}
	}
	for (i=1;i<=M-1;i++){
		for (j=1;j<=N-1;j++){
			a[i][j] = NewCells[i][j];
		}
	}

	k = 0;
	}
	

}

void user(){
	char input;
	if(kbhit())  // 判断是否有输入
	{
		input = getch();  	
			if (input == 'a')   
				speed = speed - 1;  // jiasu
			if (input == 'd')
				speed = speed + 1;  // jiansu
	}
		
}

int main()
{
	start();
	while (1){
		user();
		update();
		show();
	}
	

	
	return 0;
	
}

